// 1.声明构造函数
function Axios(config) {
    // 初始化
    this.default = config;
    this.interceptors = {
        request: new InterceptorManager(), 
        response: new  InterceptorManager()
    }
}
// 拦截器管理器构造函数
function InterceptorManager() {
    this.handlers = [];
}
InterceptorManager.prototype.use = function(fulfilled, rejected){
    this.handlers.push({fulfilled, rejected})
}

// 发送请求 难点与重点
Axios.prototype.request = function(config){
    // 创建一个promise对象
    let promise = Promise.resolve(config);
    const chains = [dispatchRequest, undefined];
    // 处理拦截器
    // 请求拦截器，将请求拦截器的回调，压入到chains的前面，request.handlers = []
    this.interceptors.request.handlers.forEach(item => {
        chains.unshift(item.fulfilled, item.rejected);
    })
    // 响应拦截器
    this.interceptors.response.handlers.forEach(item => {
        chains.push(item.fulfilled, item.rejected);
    })

    while(chains.length) {
        promise = promise.then(chains.shift(), chains.shift());
    }
    return promise;
}

function dispatchRequest(config) {
    return new Promise((resolve, reject) => {
        reject({
            status: 200,
            statusText: '111'
        })
    })
}

let context = new Axios({});
let axios = Axios.prototype.request.bind(context);

// 将context属性添加到axios

Object.keys(context).forEach(key => {
    axios[key] = context[key];
})

// 以下为测试代码
axios.interceptors.request.use(function one(config) {
    console.log(config)
}, function one(err){
    console.log(err)
})
axios.interceptors.response.use(function one(config) {
    console.log(config)
    return  config
}, function one(err){
    console.log(err)
})
axios({method: 'get', url: 'http://localhost:3000/posts'}).then(res => {
    console.log(res);
}).catch(err => {
    console.log(err)
})